package system

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzsystemconfig"
	"private-domain-overseas-service/tools/ent/predicate"
)

type SystemConfigDao struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSystemConfigDao(ctx context.Context, svcCtx *svc.ServiceContext) *SystemConfigDao {
	return &SystemConfigDao{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// SystemConfigCreate - 添加配置
func (l *SystemConfigDao) SystemConfigCreate(Config *ent.HzSystemConfig, tx *ent.Tx) error {
	clientDao := l.svcCtx.Orm.HzSystemConfig
	if tx != nil {
		clientDao = tx.HzSystemConfig
	}
	err := clientDao.Create().
		SetSystemKey(Config.SystemKey).
		SetSystemValue(Config.SystemValue).
		SetSystemDescription(Config.SystemDescription).
		SetCreatedAt(Config.CreatedAt).
		SetUpdateAt(Config.UpdateAt).
		Exec(l.ctx)
	if err != nil {
		return err
	}
	return nil
}

// SystemConfigUpdate - 修改配置
func (l *SystemConfigDao) SystemConfigUpdate(Config *ent.HzSystemConfig, tx *ent.Tx) error {
	clientDao := l.svcCtx.Orm.HzSystemConfig
	if tx != nil {
		clientDao = tx.HzSystemConfig
	}
	err := clientDao.UpdateOneID(Config.ID).
		SetSystemKey(Config.SystemKey).
		SetSystemValue(Config.SystemValue).
		SetSystemDescription(Config.SystemDescription).
		SetUpdateAt(Config.UpdateAt).
		Exec(l.ctx)
	if err != nil {
		return err
	}
	return nil
}

// SystemConfigDelete - 删除版本
func (l *SystemConfigDao) SystemConfigDelete(Config *ent.HzSystemConfig, tx *ent.Tx) error {
	clientDao := l.svcCtx.Orm.HzSystemConfig
	if tx != nil {
		clientDao = tx.HzSystemConfig
	}
	_, err := clientDao.UpdateOneID(Config.ID).
		SetDeleteAt(Config.DeleteAt).
		Save(l.ctx)
	if err != nil {
		return err
	}
	return nil
}

// SystemConfigConditionsAllByPage - 分页查询配置信息
func (l *SystemConfigDao) SystemConfigConditionsAllByPage(conditions []predicate.HzSystemConfig, current, pageSize int64) ([]*ent.HzSystemConfig, int64, error) {
	query := l.svcCtx.Orm.HzSystemConfig.Query().Where(conditions...)

	total, err := query.Count(l.ctx)
	if err != nil {
		return nil, 0, err
	}

	records, err := query.
		Offset(int((current - 1) * pageSize)).
		Order(ent.Desc(hzsystemconfig.FieldID)).
		Limit(int(pageSize)).
		All(l.ctx)
	if err != nil {
		return nil, 0, err
	}

	return records, int64(total), nil

}
